/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.escom.healthlc.utils;

import com.escom.healthlc.entidad.EnfermedadVO;
import com.escom.healthlc.entidad.HistoriaFamiliarVO;
import com.escom.healthlc.entidad.ParentescoVO;
import java.lang.reflect.Field;
import java.util.Comparator;
import org.primefaces.model.SortOrder;

/**
 *
 * @author Carlos
 */
public class LazySorterHistoria implements Comparator<HistoriaFamiliarVO> {

    private String sortField;

    private SortOrder sortOrder;

    public LazySorterHistoria(String sortField, SortOrder sortOrder) {
        this.sortField = sortField;
        this.sortOrder = sortOrder;
    }

    @Override
    public int compare(HistoriaFamiliarVO historia1, HistoriaFamiliarVO historia2) {
        try {
            Object value1 = null;
            Object value2 = null;
            Field field1;
            Field field2;
            String compere = sortField;
            if (sortField.contains("enfermedad")) {
                compere = compere.replace("enfermedad.", "");
                EnfermedadVO enfermedad1 = historia1.getEnfermedad();
                EnfermedadVO enfermedad2 = historia2.getEnfermedad();
                
                field1 = enfermedad1.getClass().getDeclaredField(compere);
                field2 = enfermedad2.getClass().getDeclaredField(compere);
                field1.setAccessible(true);
                field2.setAccessible(true);
                value1 = field1.get(enfermedad1);
                value2 = field2.get(enfermedad2);
            }
            else if (sortField.contains("parentesco")) {
                compere = compere.replace("parentesco.", "");
                ParentescoVO parentesco1 = historia1.getParentesco();
                ParentescoVO parentesco2 = historia2.getParentesco();
                
                field1 = parentesco1.getClass().getDeclaredField(compere);
                field2 = parentesco2.getClass().getDeclaredField(compere);
                field1.setAccessible(true);
                field2.setAccessible(true);
                value1 = field1.get(parentesco1);
                value2 = field2.get(parentesco2);
            }

            int value = ((Comparable) value1).compareTo(value2);

            return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
